package com.jsshse.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.sun.mail.smtp.SMTPSendFailedException;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkService {
	private static Logger log = Logger.getLogger(FreeMarkService.class);
	private JavaMailSender sender;
	private FreeMarkerConfigurer freeMarkerConfigurer = null;

	public void setFreeMarkerConfigurer(
			FreeMarkerConfigurer freeMarkerConfigurer) {
		this.freeMarkerConfigurer = freeMarkerConfigurer;
	}
 
	private String getMailText(Map param) {
		String htmlText = "";
		Map map = new HashMap();
		map.put("param", param);
		Template tpl = null;
		try {
			Configuration cfg =freeMarkerConfigurer.getConfiguration();			
			tpl = cfg.getTemplate(param.get("ftlName").toString());
			htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl,map);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		return htmlText;
	}

	public boolean sendTemplate(MailSenderInfo info)  {
		boolean flag = false;
		try {
			MimeMessage msg = sender.createMimeMessage();
			MimeMessageHelper helper;
			helper = new MimeMessageHelper(msg, false, "UTF-8");
			log.debug(info.getToAddress());
			InternetAddress[] iaToList = new InternetAddress().parse(info.getToAddress());
			msg.setRecipients(Message.RecipientType.TO, iaToList);
			helper.setSubject(info.getSubject());
			helper.setFrom(info.getFromAddress());
			helper.setText(this.getMailText(info.getParam()), true);
			sender.send(msg);
			flag=true;
		} catch (SMTPSendFailedException e) {
			e.printStackTrace();
		} catch (MailSendException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}		
		return flag;

	}

	public void setSender(JavaMailSender sender) {
		this.sender = sender;
	}

}
